package com.landeb.shop.huo.frag;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.landeb.shop.R;
import com.landeb.shop.huo.GlideCircleTransform;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.act.AccountBalanceActivity;
import com.landeb.shop.huo.act.ChargeActivity;
import com.landeb.shop.huo.act.GoodsCollectionActivity;
import com.landeb.shop.huo.act.HistoryActivity;
import com.landeb.shop.huo.act.Html5Activity;
import com.landeb.shop.huo.act.LoginActivity;
import com.landeb.shop.huo.act.MoneyLogActivity;
import com.landeb.shop.huo.act.MyOrderActivity;
import com.landeb.shop.huo.act.ProfileEditActivity;
import com.landeb.shop.huo.act.RechargeLogActivity;
import com.landeb.shop.huo.act.ScoreLogActivity;
import com.landeb.shop.huo.act.SettingActivity;
import com.landeb.shop.huo.act.ShopsCollectionActivity;
import com.landeb.shop.huo.bean.BeanStatusInfo;
import com.landeb.shop.huo.bean.BeanUserData;
import com.landeb.shop.huo.httpRequest.UserConfirmationRequest;

import cn.bingoogolapple.badgeview.BGABadgeLinearLayout;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class MineFragment extends Fragment implements View.OnClickListener {
    private static final String BASE_URL = "baseUrl";

    private View view;

    private String mBaseUrl;

    private RelativeLayout mLayoutTop;
    private TextView tvNickName;
    private ImageView ivSetting, ivMessage, ivHeadPic;

    private LinearLayout llAllOrder;
    private BGABadgeLinearLayout llToPay, llToSend, llToReceive, llToComment;

    private LinearLayout mShopsCollection, mGoodsCollection, mHistory;

    private LinearLayout llZhangHuYuE, llChongZhiJiLu, llJiFenMingXi, llZaiXianChongZhi,
            llZiJinMingXi, llQianDao,
            llJiHuoVip, llJiaRuTuiGuangRen, llWoYaoTuiGuang, llWoDeTuiGuang, llShouHuoDiZhi;

    private String mUrl;
    private Retrofit mRetrofit;
    private UserConfirmationRequest mRequest;

    private boolean isLoaded = false;
    private boolean isViewPrepared = false; // 标识fragment视图已经初始化完毕

    public MineFragment() {
        // Required empty public constructor
    }

    public static MineFragment newInstance(String baseUrl) {
        MineFragment fragment = new MineFragment();
        Bundle args = new Bundle();
        args.putString(BASE_URL, baseUrl);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mBaseUrl = getArguments().getString(BASE_URL);
        }

        OkHttpClient client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(UserConfirmationRequest.class);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_mine, container, false);

        initView();
        initData();
        initEvent();

//        llToReceive.showTextBadge("123");

        isViewPrepared = true;
        if (!isLoaded && getUserVisibleHint()) {
            refresh();
            isLoaded = true;
        }

        return view;
    }

    private void initEvent() {
        mLayoutTop.setOnClickListener(this);
        ivSetting.setOnClickListener(this);
        ivMessage.setOnClickListener(this);

        llAllOrder.setOnClickListener(this);
        llToPay.setOnClickListener(this);
        llToSend.setOnClickListener(this);
        llToReceive.setOnClickListener(this);
        llToComment.setOnClickListener(this);

        mGoodsCollection.setOnClickListener(this);
        mShopsCollection.setOnClickListener(this);
        mHistory.setOnClickListener(this);

        llZhangHuYuE.setOnClickListener(this);
        llChongZhiJiLu.setOnClickListener(this);
        llJiFenMingXi.setOnClickListener(this);
        llZaiXianChongZhi.setOnClickListener(this);
        llZiJinMingXi.setOnClickListener(this);
        llQianDao.setOnClickListener(this);


        llJiHuoVip.setOnClickListener(this);
        llJiaRuTuiGuangRen.setOnClickListener(this);
        llWoYaoTuiGuang.setOnClickListener(this);
        llWoDeTuiGuang.setOnClickListener(this);
        llShouHuoDiZhi.setOnClickListener(this);

    }

    private void initData() {

    }

    private void initView() {
        mLayoutTop = (RelativeLayout) view.findViewById(R.id.frag_mine_lr_top);
        ivHeadPic = (ImageView) view.findViewById(R.id.frag_mine_iv_head_pic);
        ivSetting = (ImageView) view.findViewById(R.id.frag_mine_iv_setting);
        ivMessage = (ImageView) view.findViewById(R.id.frag_mine_iv_msg);

        tvNickName = (TextView) view.findViewById(R.id.frag_mine_tv_nickName);

        llAllOrder = (LinearLayout) view.findViewById(R.id.frag_mine_ll_allOrders);
        llToPay = (BGABadgeLinearLayout) view.findViewById(R.id.frag_mine_ll_toPay);
        llToSend = (BGABadgeLinearLayout) view.findViewById(R.id.frag_mine_ll_toSend);
        llToReceive = (BGABadgeLinearLayout) view.findViewById(R.id.frag_mine_ll_toReceive);
        llToComment = (BGABadgeLinearLayout) view.findViewById(R.id.frag_mine_ll_toComment);

        mShopsCollection = (LinearLayout) view.findViewById(R.id.frag_mine_ll_shops_collection);
        mGoodsCollection = (LinearLayout) view.findViewById(R.id.frag_mine_ll_goods_collection);
        mHistory = (LinearLayout) view.findViewById(R.id.frag_mine_ll_history);

        llZhangHuYuE = (LinearLayout) view.findViewById(R.id.frag_mine_ll_zhanghuyue);
        llChongZhiJiLu = (LinearLayout) view.findViewById(R.id.frag_mine_ll_chongzhijilu);
        llJiFenMingXi = (LinearLayout) view.findViewById(R.id.frag_mine_ll_jifenmingxi);
        llZaiXianChongZhi = (LinearLayout) view.findViewById(R.id.frag_mine_ll_zaixianchongzhi);
        llZiJinMingXi = (LinearLayout) view.findViewById(R.id.frag_mine_ll_zijinmingxi);
        llQianDao = (LinearLayout) view.findViewById(R.id.frag_mine_ll_qiandao);

        llJiHuoVip = (LinearLayout) view.findViewById(R.id.frag_mine_ll_jihuovip);
        llJiaRuTuiGuangRen = (LinearLayout) view.findViewById(R.id.frag_mine_ll_jiarutuiguangren);
        llWoYaoTuiGuang = (LinearLayout) view.findViewById(R.id.frag_mine_ll_woyaotuiguang);
        llWoDeTuiGuang = (LinearLayout) view.findViewById(R.id.frag_mine_ll_wodetuiguang);

        llShouHuoDiZhi = (LinearLayout) view.findViewById(R.id.frag_mine_ll_shouhuodizhi);

    }

    private void refresh() {

        mRequest.getUserInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BeanUserData>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BeanUserData beanUserData) {

                        if (beanUserData.getStatus() == 1) {

                            tvNickName.setText(beanUserData.getData().getNickname());

                            String headPicUrl = "http://shop.xuji.cm:8080/index.php/Api/Public/user_head/uid/" + beanUserData.getData().getId();
                            Glide.with(getContext()).load(headPicUrl).transform(new GlideCircleTransform(getContext())).into(ivHeadPic);

                            MyApplication.mUserInfo = beanUserData.getData();

                        } else {
                            Toast.makeText(getActivity(), beanUserData.getInfo(), Toast.LENGTH_SHORT).show();
                        }


                    }
                });

    }

    private void sign() {

        mRequest.sign()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BeanStatusInfo>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BeanStatusInfo beanStatusInfo) {
                        Toast.makeText(getActivity(), beanStatusInfo.getInfo(), Toast.LENGTH_SHORT).show();
                    }
                });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.frag_mine_lr_top:
                // TODO: 2016/11/9 点击账户 跳转登陆

                SharedPreferences preferences = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
                String token = preferences.getString("token", "null");

                if (token.equals("null")) {
                    LoginActivity.toAct(getContext());
                } else {
                    ProfileEditActivity.toAct(getContext());
                }


                break;
            case R.id.frag_mine_iv_setting:
                // TODO: 2016/11/9  设置按钮

                SettingActivity.toAct(getContext());

                break;
            case R.id.frag_mine_ll_goods_collection:
                // TODO: 2016/11/9 收藏的商品

                GoodsCollectionActivity.toAct(getContext());

                break;

            case R.id.frag_mine_ll_shops_collection:
                // TODO: 2016/11/9 收藏的店铺
                ShopsCollectionActivity.toAct(getContext());
                break;

            case R.id.frag_mine_ll_history:
                // TODO: 2016/11/9 浏览历史
                HistoryActivity.toAct(getContext());
                break;

            case R.id.frag_mine_iv_msg:
                // TODO: 2016/11/9 消息按钮
                break;

            case R.id.frag_mine_ll_allOrders:
                // TODO: 2016/11/9 全部订单
                MyOrderActivity.toAct(getContext(), 0);
                break;

            case R.id.frag_mine_ll_toPay:
                // TODO: 2016/11/9 待付款
                MyOrderActivity.toAct(getContext(), 1);

                break;

            case R.id.frag_mine_ll_toSend:
                // TODO: 2016/11/9 待发货
                MyOrderActivity.toAct(getContext(), 2);

                break;

            case R.id.frag_mine_ll_toReceive:
                // TODO: 2016/11/9 待收货
                MyOrderActivity.toAct(getContext(), 3);

                break;

            case R.id.frag_mine_ll_toComment:
                // TODO: 2016/11/9 待评价
                MyOrderActivity.toAct(getContext(), 4);

                break;

            case R.id.frag_mine_ll_zhanghuyue:
                // TODO: 2017/4/13 账户余额
                AccountBalanceActivity.toAct(getActivity());
                break;

            case R.id.frag_mine_ll_chongzhijilu:
                // TODO: 2017/4/13 充值记录
                RechargeLogActivity.toAct(getActivity());
                break;

            case R.id.frag_mine_ll_jifenmingxi:
                // TODO: 2017/4/13 积分明细
                ScoreLogActivity.toAct(getActivity());
                break;

            case R.id.frag_mine_ll_zaixianchongzhi:
                // TODO: 2017/4/13 在线充值
                ChargeActivity.toAct(getActivity());
                break;

            case R.id.frag_mine_ll_zijinmingxi:
                // TODO: 2017/4/13 资金明细
                MoneyLogActivity.toAct(getActivity());
                break;

            case R.id.frag_mine_ll_qiandao:
                // TODO: 2017/4/13 签到
                sign();
                break;
            case R.id.frag_mine_ll_jihuovip:
                // TODO: 2017/4/14 激活vip

                break;

            case R.id.frag_mine_ll_jiarutuiguangren:
                // TODO: 2017/4/14 加入推广人

                break;
            case R.id.frag_mine_ll_woyaotuiguang:
                // TODO: 2017/4/14 我要推广
                Html5Activity.toAct(getActivity(), "我要推广", "http://www.landeb.com/Wap/Index/user_invite_link.html");
                break;
            case R.id.frag_mine_ll_wodetuiguang:
                // TODO: 2017/4/14 我的推广 .
                Html5Activity.toAct(getActivity(), "我的推广", "http://www.landeb.com/Wap/Index/user_invite_lists.html");

                break;
            case R.id.frag_mine_ll_shouhuodizhi:
                // TODO: 2017/4/14 收货地址管理

                Html5Activity.toAct(getActivity(), "收货地址", "http://www.landeb.com/Wap/Index/user_address_lists.html");

                break;

        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        如果已经加载过在刷新
        if (isLoaded) {
            refresh();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {

            if (isViewPrepared) {
                refresh();
                isLoaded = true;
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        isViewPrepared = false;
        isLoaded = false;

    }

}

